<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="500" height="500"></canvas>
    <script>
      //promise 的使用
      //一.promise的三种状态 1.pending 等待 2.成功 fulfilled(resolved) 3.失败rejected
      //二.每个promise对象都有一个固有的then方法
      //then里面有两种回调
      //1.onResolved : 当promise调用resolve的时候执行 resolve参数是onResolved里的参数
      //2.onRejected: 当promise调用reject的时候执行

      //可以把回调处理的异步改成promise
      //   let canvas = document.querySelector("#mycanvas");
      //   let ctx = canvas.getContext("2d");

      //图片的加载
      //   function loadImg(src, cb) {
      //     //获取图片加载完毕之后的时刻
      //     let img = document.createElement("img");
      //     img.src = src;
      //     img.onload = function () {
      //       console.log("图片加载完毕1");
      //       cb(this);
      //     };
      //   }
      //   loadImg(
      //     "https://img0.baidu.com/it/u=981218435,2998857702&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675",
      //     function (img) {
      //       console.log("图片加载完毕了2", img);
      //       ctx.drawImage(img, 0, 0, 300, 300);
      //     }
      //   );
      //   console.log(111);

      //
      //
      //
      //promise改造
      let canvas = document.querySelector("#mycanvas");
      let ctx = canvas.getContext("2d");

      //图片的加载
      function loadImg(src) {
        return new Promise((resolve, reject) => {
          //获取图片加载完毕之后的时刻
          let img = document.createElement("img");
          img.src = src;
          img.onload = function () {
            console.log("图片加载完毕了1");
            resolve(this);
          };
          img.onerror = function () {
            console.log("图片错误");
            reject("图片加载失败了");
          };
        });
      }
      //   let src =
      //     "https://img0.baidu.com/it/u=981218435,2998857702&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675";
      let src = "https://img0.baidu.c";
      loadImg(src).then(
        function (img) {
          console.log(img); //已经加载完毕的图片对象
          ctx.drawImage(img, 0, 0, 300, 300);
        },
        function (err) {
          console.log("错误", err);
        }
      );
      console.log(111);
    </script>
  </body>
</html>
